// components/date-picker/date-picker.ts
import {
  formatNumber,
  mGetDate
} from '../../utils/util'
const date = new Date()
const years = []
const months = []
const days = []
const hours = []
const minutes = []

for (let i = date.getFullYear() - 2; i <= date.getFullYear() + 2; i++) {
  years.push(i);
}
for (let i = 1; i <= 12; i++) {
  months.push(formatNumber(i))
}
for (let i = 1; i <= 31; i++) {
  days.push(formatNumber(i))
}
for (let i = 0; i <= 23; i++) {
  hours.push(formatNumber(i))
}
for (let i = 0; i <= 59; i++) {
  minutes.push(formatNumber(i))
}
Component({
  /**
   * 组件的属性列表
   */
  lifetimes: {
    attached: function () {
      const date = new Date(this.properties.dateTime)
      const yearIndex = this.data.years.findIndex((item) => item === date.getFullYear())
      const monthIndex = this.data.months.findIndex((item) => +item === date.getMonth() + 1)
      const dayIndex = this.data.days.findIndex((item) => +item === date.getDate())
      const hourIndex = this.data.hours.findIndex((item) => +item === date.getHours())
      const minuteIndex = this.data.minutes.findIndex((item) => +item === date.getMinutes())
      const value = [yearIndex, monthIndex, dayIndex, hourIndex, minuteIndex]
      this.setData({
        value: value,
        year: date.getFullYear(),
        month: date.getMonth() + 1,
        day: date.getDate(),
        hour: date.getHours(),
        minute: date.getMinutes()
      })
    },
  },
  properties: {
    show: {
      type: Boolean,
      value: false,
    },
    dateTime: {
      type: String,
      value: "",
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    years: years,
    year: 0,
    months: months,
    month: 0,
    days: days,
    day: 0,
    hours: hours,
    hour: 0,
    minutes: minutes,
    minute: 0,
    value: [0, 0, 0, 0, 0],
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleCancle() {
      this.triggerEvent("picker", { show: false })
    },
    handleConfirm() {
      this.triggerEvent("picker", {
        show: false, date: {
          year: this.data.year,
          month: this.data.month,
          day: this.data.day,
          hour: this.data.hour,
          minute: this.data.minute,
        }
      })
    },
    bindChange(e: any) {
      const val = e.detail.value
      const year = this.data.years[val[0]]
      const month = +this.data.months[val[1]]
      const day = +this.data.days[val[2]]
      const hour = +this.data.hours[val[3]]
      const minute = +this.data.minutes[val[4]]
      const dayNum = mGetDate(year, month)
      const days = []
      for (let i = 1; i <= dayNum; i++) {
        days.push(formatNumber(i))
      }
      this.setData({
        year: year,
        month: month,
        day: day,
        hour: hour,
        minute: minute,
        days: days
      })
    }
  }
})